<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <el-row class="ml10" v-show="showSearch">
        <el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
          <el-form-item :label="$t('customer.customerName')" prop="customerName">
            <el-input :placeholder="$t('customer.inputCustomerNameTip')" style="max-width: 180px"
                      v-model="state.queryForm.customerName"/>
          </el-form-item>
          <el-form-item v-auth="'sys_customer_filter'" :label="$t('customer.contact')" prop="contact">
            <el-input :placeholder="$t('customer.inputContactTip')" style="max-width: 180px"
                      v-model="state.queryForm.contact"/>
          </el-form-item>
          <el-form-item :label="$t('customer.protectCustomer')" prop="protectCustomer">
            <el-select :placeholder="t('customer.inputSelectTip')" v-model="state.queryForm.protectCustomer">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-auth="'sys_customer_filter'" :label="$t('sysuser.username')" prop="createBy">
            <el-select class="w100" clearable  :placeholder="t('customer.inputSelectTip')" v-model="state.queryForm.createBy">
              <el-option :key="item.username" :label="item.name" :value="item.username" v-for="item in userData"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList" icon="search" type="primary">
              {{ $t('common.queryBtn') }}
            </el-button>
            <el-button @click="resetQuery" icon="Refresh">{{ $t('common.resetBtn') }}</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button @click="formDialogRef.openDialog()" class="ml10" icon="folder-add" type="primary"
                     v-auth="'sys_customer_add'">
            {{ $t('common.addBtn') }}
          </el-button>
          <el-button plain :disabled="multiple" @click="handleDelete(selectObjs)" class="ml10" icon="Delete"
                     type="danger" v-auth="'sys_customer_del'">
            {{ $t('common.delBtn') }}
          </el-button>
          <right-toolbar
              :export="'sys_customer_export'"
              @exportExcel="exportExcel"
              @queryTable="getDataList"
              class="ml10"
              style="float: right; margin-right: 20px"
              v-model:showSearch="showSearch"
          ></right-toolbar>
        </div>
      </el-row>
      <el-table
          :data="state.dataList"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          v-loading="state.loading"
          border
          :cell-style="tableStyle?.cellStyle"
          :header-cell-style="tableStyle?.headerCellStyle"
      >
        <el-table-column align="center" type="selection" width="40"/>
        <el-table-column :label="t('customer.index')" type="index" width="60"/>
        <el-table-column :label="t('customer.customerName')" prop="customerName" show-overflow-tooltip/>
        <el-table-column :label="t('customer.contact')" prop="contact" show-overflow-tooltip/>
        <el-table-column :label="t('customer.customerAddress')" prop="customerAddress" show-overflow-tooltip/>
        <el-table-column :label="t('customer.customerPhone')" prop="customerPhone" show-overflow-tooltip/>
        <el-table-column :label="t('customer.remark')" prop="remark" show-overflow-tooltip/>
        <el-table-column :label="t('customer.protectCustomer')" prop="protectCustomer" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.protectCustomer === '1'">是</el-tag>
            <el-tag type="info" v-if="scope.row.protectCustomer === '0'||scope.row.protectCustomer === null">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('customer.protectCustomerTime')" prop="protectCustomerTime" show-overflow-tooltip/>
        <el-table-column :label="t('customer.createTime')" prop="createTime" show-overflow-tooltip/>
        <el-table-column :label="t('common.action')" width="200">
          <template #default="scope">
            <el-button icon="edit-pen" @click="formDialogRef.openDialog(scope.row.customerId)" link type="primary"
                       v-auth="'sys_customer_edit'"
            >{{ $t('common.editBtn') }}
            </el-button>

            <el-button icon="delete" @click="handleDelete([scope.row.customerId])" link type="danger"
                       v-auth="'sys_customer_del'"
            >{{ $t('common.delBtn') }}
            </el-button>
            <el-button icon="Lock" v-if="scope.row.protectCustomer==0" @click="handleProtect(scope.row.customerId)" link
                       type="primary" v-auth="'sys_customer_protect'"
            >{{ $t('btn.protect') }}
            </el-button>
            <el-button icon="Unlock" v-if="scope.row.protectCustomer==1" @click="handleUnProtect(scope.row.customerId)"
                       link type="danger" v-auth="'sys_customer_unprotect'"
            >{{ $t('btn.unprotect') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination @current-change="currentChangeHandle" @size-change="sizeChangeHandle" v-bind="state.pagination"/>
    </div>

    <!-- 编辑、新增  -->
    <form-dialog @refresh="getDataList()" ref="formDialogRef"/>
  </div>
</template>

<script lang="ts" name="customer" setup>
import {BasicTableProps, useTable} from '/@/hooks/table';
import {delObj, fetchList, protect, unprotect, userList} from '/@/api/bcp/customer';
import {useMessage, useMessageBox} from '/@/hooks/message';
import {useI18n} from 'vue-i18n';

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const {t} = useI18n();

// 定义变量内容
const formDialogRef = ref();
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);
//用户姓名
const userData = ref([]) as any;

const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList,
});

//  table hook
const {getDataList, currentChangeHandle, sizeChangeHandle, downBlobFile, tableStyle} = useTable(state);

// 清空搜索条件
const resetQuery = () => {
  queryRef.value.resetFields();
  getDataList();
};

// 导出excel
const exportExcel = () => {
  downBlobFile('/admin/customer/export', state.queryForm, 'customer.xlsx');
};

// 多选事件
const handleSelectionChange = (objs: { customerId: string }[]) => {
  selectObjs.value = objs.map(({customerId}) => customerId);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm(t('common.delConfirmText'));
  } catch {
    return;
  }

  try {
    await delObj(ids);
    getDataList();
    useMessage().success(t('common.delSuccessText'));
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};
// 保护用户
const handleProtect = async (id: string) => {
  try {
    await useMessageBox().confirm(t('btn.protectText'));
  } catch {
    return;
  }

  try {
    await protect(id);
    getDataList();
    useMessage().success(t('common.optSuccessText'));
  } catch (err: any) {
    useMessage().error(err.msg);
  }
}
// 取消保护用户
const handleUnProtect = async (id: string) => {
  try {
    await useMessageBox().confirm(t('btn.unprotectText'));
  } catch {
    return;
  }

  try {
    await unprotect(id);
    getDataList();
    useMessage().success(t('common.optSuccessText'));
  } catch (err: any) {
    useMessage().error(err.msg);
  }
}
// 用户数据
const getUserData = () => {
  userList({current: 1, size: 100}).then((res) => {
    userData.value = res.data.records.filter(function(user:any) {
      return user.username !== 'admin';
    });
  });
};
// 获取用户数据
getUserData()

</script>
